#!/usr/bin/python

import psycopg2
import psycopg2.extras

preparedStatementFactories = {
'Get Character Base Info and Abilities from Primary Key' : """

PREPARE getCharacterFromPk (integer) AS 
SELECT * FROM character
WHERE pk_character = $1;
""",
'Get Character Primary Key from Character Name pattern' : """

PREPARE getCharacterPkFromCharacterName (varchar) AS
SELECT pk_character FROM character
WHERE character_name ILIKE $1;
""",
'Get Character Primary Key from Player Name pattern' : """

PREPARE getCharacterPkFromPlayerName (varchar) AS
SELECT pk_character FROM character
WHERE player_name ILIKE $1;
""",
'Get Class/Level rows from Character Primary Key' : """

PREPARE getClassLevelsFromCharPk (integer) AS
SELECT * FROM classlevel c
LEFT JOIN classdef d ON c.fk_classdef = d.pk_classdef
WHERE c.fk_character = $1;
"""
}

def cleanquotes(val):
    if val is None: return ''
    return str(val).replace("'","\\'").replace('"','\\"')

conn = psycopg2.connect("dbname=postgres user=postgres")
dict_cur = conn.cursor(cursor_factory=psycopg2.extras.DictCursor)

# set up prepared statements (only valid per session)
for psf in preparedStatementFactories:
    dict_cur.execute(preparedStatementFactories[psf]);

dict_cur.execute("execute getCharacterPkFromPlayerName(%s)", ('%jer%',))
pk_character = dict_cur.fetchone()['pk_character'];

# Fetch character basic info and abilities; interpolate into setter strings
dict_cur.execute("execute getCharacterFromPk(%s)",(pk_character,))
char = dict_cur.fetchone();

fieldsFromDB = [ 'character_name', 'player_name', 'race', 'level_adj', 'size', 
                 'gender', 'alignment', 'relig_deity', 'height', 'weight', 'looks' ]
basicInfoString = ''
for f in fieldsFromDB:
    basicInfoString += """
    setValueById('%s', '%s');""" % (f, cleanquotes(char[f]))

# Fetch character class/level info; create GUI per pair and populate with setters
dict_cur.execute("execute getClassLevelsFromCharPk(%s)", (pk_character,))

fieldsFromDB = [ 'class', 'level' ]
classLevelString = ''
for i in range(dict_cur.rowcount):
    classlev = dict_cur.fetchone()
    classLevelString += """
    document.getElementById('addClassLevel').onclick();"""
    for f in fieldsFromDB:
        classLevelString += """
        setValueById('%s' + maxClassLev, '%s');""" % (f, cleanquotes(classlev[f]))

# Write formatted strings into function template
populateNameTabString = """
function populateNameTab() {
    %(basicInfo)s
    %(classLevel)s    
}""" % {'basicInfo' : basicInfoString, 'classLevel' : classLevelString}

# Read javascript template and insert formatted function where specified
f = open('xsheet-nametab-template.js', 'r')
nameTabTemplate = f.read()
f.close()

nameTabText = nameTabTemplate % {'populateNameTab' : populateNameTabString}

print "Content-Type: text/plain\n\n"
print nameTabText